/**
 * Created by a1 on 2017/11/3.
 */
"use strict";
var fs = require('fs');
var formidable = require('formidable');
var common = require('../models/common.js');
var BookModel = require('../models/Book.js');//书本Schema
var MonthModel = require('../models/Month.js');//月票Schema
var RecommModel = require('../models/Recomm.js');//推荐票Schema
var UserinfoModel = require('../models/Userinfo.js');//用户信息Schema
var UsernameModel = require('../models/Username.js');//用户Schema
var AriafansnumModel = require('../models/Ariafansnum.js');//打赏Schema
var AriafansModel = require('../models/Ariafans.js');//总打赏Schema
var BookreviewModel = require('../models/Bookreview.js');//书评Schema
var UserreviewModel = require('../models/Userreview.js');//书评详情Schema

exports.user=function(req,res){
    if(req.session.username){
        res.render('user',{
            page:'user'
        });
    }else{
        res.render('login',{
            page:'login'
        });
    }
};
exports.userAccount=function (req, res, next) {
    if(req.session.username){
        res.render('account',{
            page:'account'
        });
    }else{
        res.render('login',{
            page:'login'
        });
    }
};
exports.userMsg=function (req, res, next) {
    if(req.session.username){
        res.render('msg',{
            page:'msg',
            session:true
        });
    }else{
        res.render('login',{
            page:'login'
        });
    }
};
exports.userInfo=function(req,res){
    if(req.session.username){
        res.render('info',{
            page:'info'
        });
    }else{
        res.render('login',{
            page:'login'
        });
    }
};
exports.userInfoHeadImg=function(req,res){
    if(req.session.username){
        res.render('headimg',{
            page:'headimg'
        });
    }else{
        res.render('login',{
            page:'login'
        });
    }
};
exports.addSetMonth=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid=parseInt(fields.bid);
        let month=parseInt(fields.month);
        let jianMonth=-month;
        MonthModel.findSortOne({},{mid:-1},function(err,result){
            if(err){
                res.json({"msg":'失败',"code":0});
                return;
            }
            if(result==null||result==""){
                let obj={
                    mid:1,
                    uid:req.session.uid,
                    bid:bid,
                    month:month,
                    startTime:new Date().getTime()
                };
                let data=new MonthModel(obj);
                data.save(function(err){
                    if(err){
                        res.json({"msg":'失败',"code":0});
                        return;
                    }
                    UserinfoModel.updateFn({uid:req.session.uid},{$inc:{month:jianMonth}},function(err,data){
                        if(err){
                            res.json({"msg":'失败',"code":0});
                            return;
                        }
                        BookModel.updateFn({bid:bid},{$inc:{month:month}},function(err,docs){
                            if(err){
                                res.json({"msg":'失败',"code":0});
                                return;
                            }
                            res.json({"msg":'成功',"code":1});
                        });
                    });
                });
            }else{
                let obj={
                    mid:parseInt(result.mid)+1,
                    uid:req.session.uid,
                    bid:bid,
                    month:month,
                    startTime:new Date().getTime()
                };
                let data=new MonthModel(obj);
                data.save(function(err){
                    if(err){
                        res.json({"msg":'失败',"code":0});
                        return;
                    }
                    UserinfoModel.updateFn({uid:req.session.uid},{$inc:{month:jianMonth}},function(err,data){
                        if(err){
                            res.json({"msg":'失败',"code":0});
                            return;
                        }
                        BookModel.updateFn({bid:bid},{$inc:{month:month}},function(err,docs){
                            if(err){
                                res.json({"msg":'失败',"code":0});
                                return;
                            }
                            res.json({"msg":'成功',"code":1});
                        });
                    });
                });
            }
        });
    });
};
exports.addSetRecomm=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let bid=parseInt(fields.bid);
        let recomm=parseInt(fields.recomm);
        let jianRecomm=-recomm;
        RecommModel.findSortOne({},{rid:-1},function(err,result){
            if(err){
                res.json({"msg":'失败',"code":0});
                return;
            }
            if(result==null||result==""){
                let obj={
                    rid:1,
                    uid:req.session.uid,
                    bid:bid,
                    recomm:recomm,
                    startTime:new Date().getTime()
                };
                let data=new RecommModel(obj);
                data.save(function(err){
                    if(err){
                        res.json({"msg":'失败',"code":0});
                        return;
                    }
                    UserinfoModel.updateFn({uid:req.session.uid},{$inc:{"recomm.nan":jianRecomm}},function(err,data){
                        if(err){
                            res.json({"msg":'失败',"code":0});
                            return;
                        }
                        BookModel.updateFn({bid:bid},{$inc:{recomm:recomm}},function(err,docs){
                            if(err){
                                res.json({"msg":'失败',"code":0});
                                return;
                            }
                            res.json({"msg":'成功',"code":1});
                        });
                    });
                });
            }else{
                let obj={
                    rid:parseInt(result.rid)+1,
                    uid:req.session.uid,
                    bid:bid,
                    recomm:recomm,
                    startTime:new Date().getTime()
                };
                let data=new RecommModel(obj);
                data.save(function(err){
                    if(err){
                        res.json({"msg":'失败',"code":0});
                        return;
                    }
                    UserinfoModel.updateFn({uid:req.session.uid},{$inc:{"recomm.nan":jianRecomm}},function(err,data){
                        if(err){
                            res.json({"msg":'失败',"code":0});
                            return;
                        }
                        BookModel.updateFn({bid:bid},{$inc:{recomm:recomm}},function(err,docs){
                            if(err){
                                res.json({"msg":'失败',"code":0});
                                return;
                            }
                            res.json({"msg":'成功',"code":1});
                        });
                    });
                });
            }
        });
    });
};
exports.addSetReward=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files) {
        let bid = parseInt(fields.bid);
        let reward = parseInt(fields.reward);
        let jianReward = -reward;
        AriafansnumModel.findSortOne({},{afsid:-1},function(err,result){
            if(result==null||result=="") {
                let obj = {
                    afsid: 1,
                    uid: req.session.uid,
                    bid: bid,
                    reward: reward,
                    time: new Date().getTime()
                };
                let data=new AriafansnumModel(obj);
                data.save(function(err){
                    UserinfoModel.updateFn({uid:req.session.uid},{$inc:{account:jianReward}},function(err,data){
                        if(err){
                            res.json({"msg":'失败',"code":0});
                            return;
                        }
                        AriafansModel.findSortOne({bid:bid,uid:req.session.uid},{afid:1},function(err,result1){
                            if(result1==null){
                                AriafansnumModel.sumFn([{$match:{bid:bid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc){
                                    let quihe=doc[0].he;
                                    BookModel.updateFn({bid:bid},{$set:{reward:quihe}},function(err,docs){
                                        AriafansnumModel.sumFn([{$match:{bid:bid,uid:req.session.uid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc1){
                                            let quihe=doc1[0].he;
                                            let obj = {
                                                afid: 1,
                                                uid: req.session.uid,
                                                bid: bid,
                                                reward: quihe
                                            };
                                            let data=new AriafansModel(obj);
                                            data.save(function(err){
                                                res.json({"msg":'成功',"code":1});
                                            });
                                        });
                                    });
                                });
                            }else{
                                AriafansnumModel.sumFn([{$match:{bid:bid,uid:req.session.uid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc1){
                                    let quihe=doc1[0].he;
                                    AriafansModel.updateFn({bid:bid,uid:req.session.uid},{$set:{reward:quihe}},function(err,ddd){
                                        res.json({"msg":'成功',"code":1});
                                    });
                                });

                            }
                        });
                    });
                });
            }else{
                let obj = {
                    afsid: parseInt(result.afsid)+1,
                    uid: req.session.uid,
                    bid: bid,
                    reward: reward,
                    time: new Date().getTime()
                };
                let data=new AriafansnumModel(obj);
                data.save(function(err){
                    UserinfoModel.updateFn({uid:req.session.uid},{$inc:{account:jianReward}},function(err,data){
                        if(err){
                            res.json({"msg":'失败',"code":0});
                            return;
                        }
                        AriafansModel.findSortOne({bid:bid,uid:req.session.uid},{afid:1},function(err,result1){
                            if(result1==null){
                                AriafansnumModel.sumFn([{$match:{bid:bid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc){
                                    let quihe=doc[0].he;
                                    BookModel.updateFn({bid:bid},{$set:{reward:quihe}},function(err,docs){
                                        AriafansnumModel.sumFn([{$match:{bid:bid,uid:req.session.uid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc1){
                                            let quihe=doc1[0].he;
                                            AriafansModel.findSortOne({},{afid:-1},function(err,res1){
                                                let obj = {
                                                    afid: parseInt(res1.afid)+1,
                                                    uid: req.session.uid,
                                                    bid: bid,
                                                    reward: quihe
                                                };
                                                let data=new AriafansModel(obj);
                                                data.save(function(err){
                                                    res.json({"msg":'成功',"code":1});
                                                });
                                            });
                                        });
                                    });
                                });
                            }else{
                                AriafansnumModel.sumFn([{$match:{bid:bid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc) {
                                    let quihe = doc[0].he;
                                    BookModel.updateFn({bid: bid}, {$set: {reward: quihe}}, function (err, docs) {
                                        AriafansnumModel.sumFn([{$match:{bid:bid,uid:req.session.uid}},{$group:{"_id":null,"he":{$sum:"$reward"}}}],function(err,doc1){
                                            let quihe=doc1[0].he;
                                            AriafansModel.updateFn({bid:bid,uid:req.session.uid},{$set:{reward:quihe}},function(err,ddd){
                                                res.json({"msg":'成功',"code":1});
                                            });
                                        });
                                    });
                                });
                            }
                        });
                    });
                });
            }
        });
    });
};
exports.getMonthList=function(req,res){
    MonthModel.findFnLimit({uid:req.session.uid},{startTime:-1},30,function(err,docs){
        if(err){
            res.json({"msg":'失败',"code":0,info:{}});
            return;
        }
        if(docs==null){
            res.json({"msg":'失败',"code":0,info:{monthArr:[],bookArr:[]}});
        }else{
            let obj={};
            let arrbook=[];
            (function bl(i){
                i++;
                if(i==docs.length){
                    obj.monthArr=docs;
                    obj.bookArr=arrbook;
                    res.json({"msg":'成功',"code":1,info:obj});
                    return;
                }else{
                    BookModel.findSortOne({"bid":docs[i]['bid']},{"bid":1},function(err,data){
                        //console.log(data1);
                        arrbook.push(data);
                        bl(i);
                    });
                }
            }(-1));
        }
    });
};
exports.getRecommList=function(req,res){
    RecommModel.findFnLimit({uid:req.session.uid},{startTime:-1},30,function(err,docs){
        if(err){
            res.json({"msg":'失败',"code":0,info:{}});
            return;
        }
        if(docs==null){
            res.json({"msg":'失败',"code":0,info:{monthArr:[],bookArr:[]}});
        }else{
            let obj={};
            let arrbook=[];
            (function bl(i){
                i++;
                if(i==docs.length){
                    obj.monthArr=docs;
                    obj.bookArr=arrbook;
                    res.json({"msg":'成功',"code":1,info:obj});
                    return;
                }else{
                    BookModel.findSortOne({"bid":docs[i]['bid']},{"bid":1},function(err,data){
                        //console.log(data1);
                        arrbook.push(data);
                        bl(i);
                    });
                }
            }(-1));
        }
    });
};
exports.getRewardList=function(req,res){
    AriafansnumModel.findFnLimit({uid:req.session.uid},{time:-1},30,function(err,docs){
        if(err){
            res.json({"msg":'失败',"code":0,info:{}});
            return;
        }
        if(docs==null){
            res.json({"msg":'失败',"code":0,info:{monthArr:[],bookArr:[]}});
        }else{
            let obj={};
            let arrbook=[];
            (function bl(i){
                i++;
                if(i==docs.length){
                    obj.monthArr=docs;
                    obj.bookArr=arrbook;
                    res.json({"msg":'成功',"code":1,info:obj});
                    return;
                }else{
                    BookModel.findSortOne({"bid":docs[i]['bid']},{"bid":1},function(err,data){
                        //console.log(data1);
                        arrbook.push(data);
                        bl(i);
                    });
                }
            }(-1));
        }
    });
};
exports.updateHeadImg=function(req,res){
    if(!req.session.uid){
        res.json({code:2,msg:"你还未登录"})
    }else{
        var form = new formidable.IncomingForm();//创建表单
        form.parse(req,function(err,fields,files) {
            let bs64img = fields.image;
            var base64Data = bs64img.replace(/^data:image\/\w+;base64,/, "");
            var dataBuffer = new Buffer(base64Data, 'base64');
            let sjs="head_"+new Date().getTime()+""+(Math.random()*90000+10000).toFixed(0);
            let p1=new Promise(function(resolve,reject){
                fs.writeFile("./public/up/images/head/"+sjs+".png", dataBuffer, function(err) {
                    if(err){
                        reject(err)
                    }else{
                        resolve("/up/images/head/"+sjs+".png");
                    }
                });
            });
            p1.then(function(res1){
                UserinfoModel.updateFn({uid:req.session.uid},{$set:{imgurl:res1}},function(err,doc){
                    if(err){
                        res.json({code:3,msg:"写入数据库失败"})
                    }else{
                        res.json({code:1,msg:"上传成功",imgurl:res1});
                    }
                })
            },function(res){
                res.json({code:0,msg:"上传失败"})
            })
        })
    }
};
exports.setUserInfo=function(req,res){
    if(!req.session.uid){
        res.json({code:2,msg:"你还未登录"})
    }else{
        var form = new formidable.IncomingForm();//创建表单
        form.parse(req,function(err,fields,files) {
            let type=fields.type;
            let val=fields.value;
            if(type=='nickname'){
                UserinfoModel.updateFn({uid:req.session.uid},{$set:{nickname:val}},function(err,doc){
                    if(err){
                        res.json({code:0,msg:"昵称修改失败"})
                    }else{
                        res.json({code:1,msg:"昵称修改成功"});
                    }
                })
            }else if(type=='age'){
                UsernameModel.updateFn({uid:req.session.uid},{$set:{age:val}},function(err,doc){
                    if(err){
                        res.json({code:0,msg:"年龄修改失败"})
                    }else{
                        res.json({code:1,msg:"年龄修改成功"});
                    }
                })
            }else if(type=='sex'){
                UsernameModel.updateFn({uid:req.session.uid},{$set:{sex:val}},function(err,doc){
                    if(err){
                        res.json({code:0,msg:"性别修改失败"})
                    }else{
                        res.json({code:1,msg:"性别修改成功"});
                    }
                })
            }else if(type=='desc'){
                UserinfoModel.updateFn({uid:req.session.uid},{$set:{desc:val}},function(err,doc){
                    if(err){
                        res.json({code:0,msg:"简介修改失败"})
                    }else{
                        res.json({code:1,msg:"简介修改成功"});
                    }
                })
            }
        })
    }
};
exports.getMsgUserCount=function(req,res){
    let p1=new Promise(function(reslove,reject){
        BookreviewModel.findConut({uid:req.session.uid},function(err,count){
            if(err){
                reject(err);
                return;
            }
            reslove(count);
        });
    });
    p1.then(function(count){
        res.json({"msg":'成功',"code":1,count:count});
    },function(err){
        res.json({"msg":'失败',"code":0,count:0});
    })
};
exports.getMsgUserSubCount=function(req,res){
    let p1=new Promise(function(reslove,reject){
        UserreviewModel.findConut({uid:req.session.uid},function(err,count){
            if(err){
                reject(err);
                return;
            }
            reslove(count);
        });
    });
    p1.then(function(count){
        res.json({"msg":'成功',"code":1,count:count});
    },function(err){
        res.json({"msg":'失败',"code":0,count:0});
    })
};
exports.getMsgUserPinglun=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files) {
        let page = parseInt(fields.page);
        let pagenum = page * 10;
        let p1=new Promise(function(reslove,reject){
            BookreviewModel.findLimitSkip({uid:req.session.uid},10,pagenum,{startTime:-1},function(err,resDocs){
                if(err){
                    reject(err);
                    return;
                }
                reslove(resDocs);
            });
        });
        p1.then(function(result){
            UserinfoModel.findSortOne({uid:req.session.uid},{uid:1},function(err,doc){
                if(err){
                    res.json({code:0,msg:"失败",info:{userinfo:{},bookArr:[],data:[]}});
                    return;
                }
                let bookArr=[];
                (function bl1(i){
                    i++;
                    if(i==result.length){
                        res.json({code:1,msg:"成功",info:{userinfo:doc,bookArr:bookArr,data:result}});
                        return;
                    }else{
                        BookModel.findSortOne({"bid":result[i]['bid']},{"bid":1},function(err,doc1){
                            bookArr.push(doc1);
                            bl1(i);
                        });
                    }
                })(-1);
            });
        },function(err){
            res.json({code:0,msg:"失败",info:{userinfo:{},bookArr:[],data:[]}});
        });
    });
};
exports.getMsgUserHuifu=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files) {
        let page = parseInt(fields.page);
        let pagenum = page * 10;
        let p1=new Promise(function(reslove,reject){
            UserreviewModel.findLimitSkip({uid:req.session.uid},10,pagenum,{startTime:-1},function(err,resDocs){
                if(err){
                    reject(err);
                    return;
                }
                reslove(resDocs);
            });
        });
        p1.then(function(result){
            UserinfoModel.findSortOne({uid:req.session.uid},{uid:1},function(err,doc){
                if(err){
                    res.json({code:0,msg:"失败",info:{userinfo:{},bookArr:[],data:[]}});
                    return;
                }
                let bookArr=[];
                (function bl1(i){
                    i++;
                    if(i==result.length){
                        res.json({code:1,msg:"成功",info:{userinfo:doc,bookArr:bookArr,data:result}});
                        return;
                    }else{
                        BookModel.findSortOne({"bid":result[i]['bid']},{"bid":1},function(err,doc1){
                            bookArr.push(doc1);
                            bl1(i);
                        });
                    }
                })(-1);
            });
        },function(err){
            res.json({code:0,msg:"失败",info:{userinfo:{},bookArr:[],data:[]}});
        });
    });
};
exports.getMsgUserList=function(req,res){
    var form = new formidable.IncomingForm();//创建表单
    form.parse(req,function(err,fields,files){
        let p1=new Promise(function(reslove,reject){
            BookreviewModel.findFn({uid:req.session.uid},{brid:1},function(err,resDocs){
                if(err){
                    reject(err);
                    return;
                }
                reslove(resDocs);
            });
        });
        p1.then(function(result){
            //console.log(result);
            let data=[];
            (function bl(i){
                i++;
                if(i==result.length){
                    if(data==""){
                        res.json({"msg":'成功',"code":1,info:{data:[],userInfo:{userimg:[],usernick:[]},bookArr:[]}});
                    }else{
                        let arrimg=[];
                        let arrnick=[];
                        (function bl1(j){
                            j++;
                            if(j==data.length){
                                let bookArr=[];
                                (function bl2(k){
                                    k++;
                                    if(k==data.length){
                                        let brforum=[];
                                        (function bl3(l){
                                            l++;
                                            if(l==data.length){
                                                let bruser=[];
                                                (function bl4(m){
                                                    m++;
                                                    if(m==brforum.length){
                                                        res.json({"msg":'成功',"code":1,info:{data:data,userInfo:{userimg:arrimg,usernick:arrnick},bookArr:bookArr,brforum:brforum,bruser:bruser}});
                                                        return;
                                                    }else{
                                                        UserinfoModel.findSortOne({uid:brforum[m]['uid']},{uid:1},function(err,doc2){
                                                            bruser.push(doc2);
                                                            bl4(m);
                                                        })
                                                    }
                                                })(-1);
                                                return;
                                            }else{
                                                BookreviewModel.findSortOne({brid:data[l]['brid']},{brid:1},function(err,doc2){
                                                    brforum.push(doc2);
                                                    bl3(l);
                                                })
                                            }
                                        })(-1);
                                        return;
                                    }else{
                                        BookModel.findSortOne({"bid":data[k]['bid']},{"bid":1},function(err,doc1){
                                            //console.log(data1);
                                            bookArr.push(doc1);
                                            bl2(k);
                                        });
                                    }
                                })(-1);
                                return;
                            }else{
                                UserinfoModel.findSortOne({"uid":data[j]['uid']},{"uid":1},function(err,docs){
                                    //console.log(data1);
                                    arrimg.push(docs['imgurl']);
                                    arrnick.push(docs['nickname']);
                                    bl1(j);
                                });
                            }
                        }(-1));
                    }
                    return;
                }else{
                    UserreviewModel.findFn({brid:result[i]['brid'],"uid":{$ne:req.session.uid}},{urid:1},function(err,docsArr){
                        if(docsArr==null){
                            data=data.concat([]);
                        }else{
                            data=data.concat(docsArr);
                        }
                        bl(i);
                    });
                }
            }(-1));
        });
    });
};